<template>
  <div class="app-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h3>{{ isEdit ? '编辑患者' : '新增患者' }}</h3>
        </div>
      </template>
      
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="120px"
        label-position="right"
        status-icon
      >
        <el-divider content-position="left">基本信息</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入患者姓名" />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="form.gender" placeholder="请选择性别" style="width: 100%">
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="出生日期" prop="birthDate">
              <el-date-picker 
                v-model="form.birthDate" 
                type="date" 
                placeholder="选择出生日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idNumber">
              <el-input 
                v-model="form.idNumber" 
                placeholder="请输入身份证号"
                maxlength="18"
                :disabled="isEdit"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="状态" prop="activeStatus">
              <el-switch
                v-model="form.activeStatus"
                active-text="有效"
                inactive-text="无效"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">联系信息</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="手机号" prop="contactInfo.phone">
              <el-input 
                v-model="form.contactInfo.phone" 
                placeholder="请输入手机号"
                maxlength="11"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="紧急联系人" prop="contactInfo.emergencyContact">
              <el-input v-model="form.contactInfo.emergencyContact" placeholder="请输入紧急联系人" />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="家庭住址" prop="contactInfo.address">
              <el-input v-model="form.contactInfo.address" placeholder="请输入家庭住址" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">医疗信息</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="血型" prop="medicalInfo.bloodType">
              <el-select 
                v-model="form.medicalInfo.bloodType" 
                placeholder="请选择血型"
                style="width: 100%"
              >
                <el-option label="A型" value="A" />
                <el-option label="B型" value="B" />
                <el-option label="AB型" value="AB" />
                <el-option label="O型" value="O" />
                <el-option label="A+型" value="A+" />
                <el-option label="A-型" value="A-" />
                <el-option label="B+型" value="B+" />
                <el-option label="B-型" value="B-" />
                <el-option label="AB+型" value="AB+" />
                <el-option label="AB-型" value="AB-" />
                <el-option label="O+型" value="O+" />
                <el-option label="O-型" value="O-" />
                <el-option label="未知" value="未知" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="过敏史" prop="medicalInfo.allergies">
              <el-select 
                v-model="form.medicalInfo.allergies" 
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请输入过敏史，可多选"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="慢性病史" prop="medicalInfo.chronicDiseases">
              <el-select 
                v-model="form.medicalInfo.chronicDiseases" 
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请输入慢性病史，可多选"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">保险信息</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="保险公司" prop="insuranceInfo.provider">
              <el-input v-model="form.insuranceInfo.provider" placeholder="请输入保险公司" />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="保单号" prop="insuranceInfo.policyNumber">
              <el-input v-model="form.insuranceInfo.policyNumber" placeholder="请输入保单号" />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="到期日期" prop="insuranceInfo.expiryDate">
              <el-date-picker 
                v-model="form.insuranceInfo.expiryDate" 
                type="date" 
                placeholder="选择到期日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">标签</el-divider>
        
        <el-row>
          <el-col :span="24">
            <el-form-item label="患者标签" prop="tags">
              <el-select 
                v-model="form.tags" 
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请添加标签，可自定义"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">保存</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { patientAPI } from '@/utils/api'
import { formRules } from '@/utils/validate'

const route = useRoute()
const router = useRouter()
const formRef = ref(null)
const loading = ref(false)

// 判断是新增还是编辑
const isEdit = computed(() => {
  return route.name === 'PatientEdit'
})

// 表单数据
const form = reactive({
  name: '',
  gender: '',
  birthDate: '',
  idNumber: '',
  activeStatus: true,
  contactInfo: {
    phone: '',
    emergencyContact: '',
    address: ''
  },
  medicalInfo: {
    bloodType: '未知',
    allergies: [],
    chronicDiseases: []
  },
  insuranceInfo: {
    provider: '',
    policyNumber: '',
    expiryDate: ''
  },
  tags: []
})

// 表单验证规则
const rules = reactive({
  name: [formRules.required],
  gender: [formRules.required],
  birthDate: [formRules.required],
  idNumber: [formRules.required, formRules.idNumber],
  'contactInfo.phone': [formRules.required, formRules.phone]
})

// 获取患者详情
const getPatientDetails = async (id) => {
  loading.value = true
  try {
    const res = await patientAPI.getPatient(id)
    const patientData = res.data
    
    // 表单赋值
    for (const key in form) {
      if (key === 'contactInfo' || key === 'medicalInfo' || key === 'insuranceInfo') {
        // 对象类型，需要深拷贝
        form[key] = { ...form[key], ...patientData[key] }
      } else {
        form[key] = patientData[key]
      }
    }
    
    // 日期格式转换
    if (form.birthDate) {
      form.birthDate = new Date(form.birthDate)
    }
    
    if (form.insuranceInfo.expiryDate) {
      form.insuranceInfo.expiryDate = new Date(form.insuranceInfo.expiryDate)
    }
  } catch (error) {
    console.error('获取患者详情失败', error)
    ElMessage.error('获取患者详情失败')
  } finally {
    loading.value = false
  }
}

// 提交表单
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const formData = {
          ...form,
          // 确保日期格式正确
          birthDate: form.birthDate instanceof Date ? form.birthDate.toISOString().split('T')[0] : form.birthDate,
          insuranceInfo: {
            ...form.insuranceInfo,
            expiryDate: form.insuranceInfo.expiryDate instanceof Date 
              ? form.insuranceInfo.expiryDate.toISOString().split('T')[0] 
              : form.insuranceInfo.expiryDate
          }
        }
        
        if (isEdit.value) {
          // 编辑患者
          await patientAPI.updatePatient(route.params.id, formData)
          ElMessage.success('更新患者信息成功')
        } else {
          // 创建患者
          await patientAPI.createPatient(formData)
          ElMessage.success('创建患者成功')
        }
        
        // 返回列表页
        goBack()
      } catch (error) {
        console.error(isEdit.value ? '更新失败' : '创建失败', error)
        ElMessage.error(isEdit.value ? '更新患者信息失败' : '创建患者失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 返回上一页
const goBack = () => {
  router.push('/patients/list')
}

// 页面加载时，如果是编辑模式，获取患者详情
onMounted(() => {
  if (isEdit.value && route.params.id) {
    getPatientDetails(route.params.id)
  }
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-divider {
  margin: 24px 0;
}

.el-divider__text {
  font-size: 16px;
  font-weight: bold;
  color: #409EFF;
}
</style> 